import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';

import { APIBase } from 'app/modules/base/api-base';

@Injectable({
	providedIn: 'root',
})
export class LogService {
	constructor(protected http: HttpClient) {}

	log<T>(snapshot: ActivatedRouteSnapshot): APIBase<any, T> {
		let pathInfo = ParseRouteURL(snapshot);
		let url: string = '/api/admin/logs/' + pathInfo.parent + '/' + pathInfo.path;

		let base = new APIBase<any, T>(this.http, url);
		return base;
	}
	// Dashboard use it
	resource<T>(type: 'pc_exception' | 'software' | 'pc' | 'area') {
		const url = 'api/admin/logs';
		switch (type) {
			case 'pc_exception':
				return new APIBase<any, T>(this.http, url + '/pc/exception');
			case 'software':
				return new APIBase<any, T>(this.http, url + '/human/software');
			case 'pc':
				return new APIBase<any, T>(this.http, url + '/human/pc');
			case 'area':
				return new APIBase<any, T>(this.http, url + '/area/config');
		}
	}
}

export function ParseRouteURL(route: ActivatedRouteSnapshot): LogRoutePath {
	let path: string;
	let ppath: string;
	let parent = route.parent;
	let id = route.paramMap.get('id');

	if (id == null) {
		path = route.url.join(',');
		if (parent) {
			ppath = parent.url.join(',');
		}
	} else {
		path = parent.url.join(',');
		ppath = parent.parent.url.join(',');
	}
	return { parent: ppath, path: path };
}

export enum LogType {
	HumanSoftware = 1000,
	PcException,
	PcUpgrade,
	AreaConfig,
	AreaPc,
	AreaPrivilege,
}

export enum OperationType {
	Login = 1100,
	Logout,
	Opened,
	Closed,
	HumanChanged,
	PcChanged,
	SoftwareChanged,
	PcDefaultConfig,
}

export enum TargetType {
	OS = 1200,
	Software,
}

export enum StatusType {
	Success = 1300,
	Failure,
}

export interface LogInfo {
	id: number;
	type: number;
	type_desc: string;
	created_at: string;
}

export interface LogRoutePath {
	parent: string;
	path: string;
}
